<template>
    
    <el-dialog v-model="dialog"  title="账号添加" width="500">
        <div>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
                <!-- 头像上传 -->
                <el-form-item label="头像" prop="avatar">
                    <el-upload class="avatar-uploader" :action="uploadURL" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="formData.photo" :src="formData.photo" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <!-- 姓名输入框 -->
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
                </el-form-item>

                <!-- 手机号输入框 -->
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="formData.mobile" placeholder="请输入手机号"></el-input>
                </el-form-item>

                <!-- 账号输入框 -->
                <el-form-item label="账号" prop="account">
                    <el-input v-model="formData.username" placeholder="请输入账号"></el-input>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="formData.pwd" placeholder="请输入密码"></el-input>
                </el-form-item>

                <!-- 所属角色选择框 -->
                <el-form-item label="所属角色" prop="role">
                    <el-select placeholder="请选择">
                        <el-option label="管理员" value="admin"></el-option>
                        <el-option label="普通用户" value="user"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>


        <!-- 对话框底部按钮 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="onUp(false)">关闭</el-button>
            <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        </span>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, watch, computed, type PropType } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { doEncrypt } from '@/utils/cryptoUtil';
import { addAccount, getAccount } from '@/apis/account/account';
import type { RootObject } from '@/apis/account/type';
let uploadURL: string = import.meta.env.VITE_BASE_URL + '/upload/add'

const props = defineProps({
    isId: {
        type: Number as PropType<number>,
        default: 0
    }
})
console.log('父组件传来的id',props.isId);



//setup中使用emits,需要先声明，定义属性数量
const emits = defineEmits(['dialogVisible'])
function onUp(n: boolean) {
  console.log('子组件函数')
  emits('dialogVisible', n)
}

let dialog =ref(true)
 
const formRef = ref<FormInstance | null>(null);

// 表单数据
const formData: RootObject = reactive({
    username: '',
    name: '',
    pwd: '',
    mobile: '',
    photo: '',
    enable: 1,
    roleIds: [1]
});
// 表单验证规则
const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    // phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    // account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    // password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    // role: [{ required: true, message: '请选择角色', trigger: 'change' }]
};

// 头像上传成功回调
const handleAvatarSuccess = (res: any, file: any) => {
    formData.photo = URL.createObjectURL(file.raw);
};

// 头像上传前校验
const beforeAvatarUpload = (file: any) => {
    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

// 提交表单
const submitForm = (formName: string) => {
    if (!formRef.value) {
        ElMessage.error('表单未正确初始化，请刷新页面重试');
        return;
    }

    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // alert('submit!');
            // console.log(formData);
            // 加密密码
            formData.pwd = await doEncrypt(formData.pwd);

            let res = await addAccount(formData)
            // console.log('账号添加',res);

            ElMessage.success('账号添加成功');
            // 关闭弹窗
            onUp(false)
            // 重新获取数据
            // await getAccount({page:1,pageSize:10});

        } else {
            console.log('error submit!!');
            // 不需要返回 false，直接结束函数即可
        }
    });
};

</script>

<style scoped lang='less'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>